#include "stdafx.h"
#include "MemoryBuffer.h"

 

MemoryBuffer::MemoryBuffer(QObject *parent  ):QObject(parent),
m_hit(0),m_total(0)
{
	for(int i = 0;i<MAX_ENTRY;i++)
		unused.insert(i);
}

bool MemoryBuffer::has( UINT64 start,int len )
{
	if (!m_off2index.contains(start))
		return false;
	STORE& st = m_dat[m_off2index[start]];
	bool ret = st.len>=len;
	m_hit+=ret;
	m_total++;
	return ret;
}

char * MemoryBuffer::getData( UINT64 start, UINT64 len )
{
	Q_ASSERT_X(has(start,len),"memorybuffer::getdata","has enough data to feed");
	STORE& st = m_dat[m_off2index[start]];
	return st.data;
}

void MemoryBuffer::add( UINT64 start, UINT64 len, char * target )
{
	Q_ASSERT(!has(start,len));
	if (unused.empty()) {
		//remove one
		int victim = rand()%MAX_ENTRY;
		unused.insert(victim);
		STORE&st = m_dat[victim];
		m_off2index.remove(st.start);
	}
	int nIndex = unused.begin().operator *();
	unused.erase(unused.begin());
	m_off2index[start] = nIndex;
	STORE &st = m_dat[nIndex];
	st.len=len;
	st.start = start;
	memcpy(st.data,target,len);
}

 